package com.library.controller.user;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.library.constant.MessageConstant;
import com.library.result.Result;
import com.library.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传，文件名：{}",file.getOriginalFilename());

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取原始文件名的后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成新文件名
        String objectName = UUID.randomUUID().toString() + extension;

        try {
            //上传文件到OSS
            String url = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(url);
        } catch (Exception e) {
            log.error("文件上传失败：{}",e);
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

    @GetMapping("/captcha")
    public Result<Map> getCaptcha(){
        // 生成验证码文本和图片
        String text = defaultKaptcha.createText();
        BufferedImage image = defaultKaptcha.createImage(text);

        // 生成唯一键（如UUID）
        String captchaKey = UUID.randomUUID().toString();

        // 存储到Redis（有效期5分钟）
        redisTemplate.opsForValue().set(
                "captcha:" + captchaKey,
                text,
                5,
                TimeUnit.MINUTES
        );

        // 将图片转为Base64返回给前端
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", baos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String base64Image = Base64.getEncoder().encodeToString(baos.toByteArray());

        // 返回键和图片
        Map<String, String> result = new HashMap<>();
        result.put("captchaKey", captchaKey);
        result.put("captchaImage", "data:image/jpeg;base64," + base64Image);
        return Result.success(result);
    }

}
